#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "nocopy.hpp"
#include "log.hpp"
#include "comm.hpp"


const static uint16_t defaultport = 8888;
const static int defaultfd = -1;
const static int defaultsize = 1024;

class udpserver :public nocopy
{
public:
    udpserver(const std::string& ip, uint16_t port = defaultport):_ip(ip),_port(port),_sockfd(defaultfd)
    {}
    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            lg.Logmessage(Fatal, "socket errr, %d : %s\n",errno, strerror(errno));
            exit(Socket_err);
        }
        lg.Logmessage(Info, "socket success, sockfd :%d\n",_sockfd);
        //绑定
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        
        //使用 :: 可以明确指出是调用全局作用域中的 bind 而不是某个类成员或局部作用域中的 bind。
        //但是，通常在使用 bind 系统调用时，我们不会看到 :: 前缀，除非有特定的命名冲突。
        int n = ::bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n != 0)
        {
            lg.Logmessage(Fatal, "Bind errr, %d : %s\n",errno, strerror(errno));
            exit(Bind_err);
        }
    }
    void Start()
    {
        //服务器永不退出
        char buffer[defaultsize];
        for (;;)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << "client say# " << buffer << std::endl;
                sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr*)&peer, len);
            }
        }
    }
    ~udpserver(){}
private:
    std::string _ip;
    uint16_t _port;
    int _sockfd;
};